%% test if object is initialized and can be used
ETTMat_init

%% get the list of connected devices
DeviceList=Device.ScanDeviceList;
if(DeviceList.Count<1 || DeviceList.Item(0)=='')
   disp('No devices were found, please connect a device to continue!') 
   return
end

for n=0:DeviceList.Count-1
   deviceProperties=DeviceList.Item(n).Split('.');
   sprintf('Device %d: uniqueID: %s Name: %s (Type: %s)',n+1, deviceProperties(1),deviceProperties(2),deviceProperties(3))
end

%% subscribe to inhalation onset
Device.ResetState();
if exist('el','var')
   delete(el);
end
el=addlistener(Device,'InhalationOnsetEvent',@InhalationOnset);% bind inhalation onset event / notify each event

Device.SubscribeToInhalationEvents(true,false); % first parameter to activate, second if simulation is desired, third optional device address
%  respiration feature on the Device (false will stop it again)

%% subscribe to TTL IN
% addlistener(Device,'TTLOnsetEvent',@TTLOnset)% bind to TTL In
%(external) event / notify each event
% Device.SubscribeToTTLEvents(true); % actually activates the TTL IN feature on the Device

%% sample paradigm
IsStim=0;
% for n=1:6
%     if IsStim==0 
%         IsStim=1;
%         Device.AsyncWaitForInhalationEvent(10);% new aync function with timeout in s, optional device address
% %         Device.WaitForInhalationEvent();
Device.AsyncWaitForInhalationEvent(10);
fNIRS.Marker("1")
Device.SetChannel(1,3000);

%         valveToOpen=randi([1,6]);
%         disp(sprintf('ValveID opening: %d', valveToOpen));
%         Device.SetChannel(valveToOpen,true);
%     else
%         IsStim=0;
%         Device.CloseAllChannels();
%         disp('all valves closed')
%     end
%     pause(1)
% end
Device.SetChannel(1,3000);
% pause(3)
Device.SetChannel(2,1000);
% pause(3)
Device.SetChannel(3,2000);
% Device.SubscribeToInhalationEvents(false,false);% it is good practice to deactivate respiration after done
% Device.SaveRespirationData('','0',0)% save all respiration data to csv file on desktop
%% events can be used to asynchronously interact with device features
%function InhalationOnset(~,arg)
    %sprintf('Inhalation onset: %s', arg.TimeText)
%    disp('sniff')
%    sprintf('Inhalation onset: %s --> %d', arg.TimeText,arg.DeviceTime) % just print the timestamp of the event
%   assignin('base','k',arg.ID) % one could assign a variable in the
%   default workspace to trigger further processing
%   assignin('base','IsInhaling',1)
%end

%function TTLOnset(~,arg)
%    sprintf('TTL IN onset: %s', arg.TimeText) % just print the timestamp of the event
%   assignin('base','k',arg.ID) % one could assign a variable in the
%   default workspace to trigger further processing
%   assignin('base','IsTriggering',1)
%end